﻿using System.Collections.Generic;
using IDAL;
using Model;
using NHibernate;

namespace SqlDALLibrary
{
    public class UserDal : IUserDAL
    {
        private static EntityControl control;

        static UserDal()
        {
            control = EntityControl.CreateEntityControl("Model");
        }

        public void saveUser(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Save(user);
                tx.Commit();
            }
            session.Close();
        }

        public void updateUser(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Update(user);
                tx.Commit();
            }
            session.Close();
        }

        public void deleteUser(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Delete(user);
                tx.Commit();
            }
            session.Close();
        }

        public User getUserById(int id)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            User user = session
                   .CreateQuery("from User u where u.id=:id")
                .SetInt32("id", id)
                .UniqueResult<User>();
            session.Close();
            return user;
        }

        public User getUserByEmail(string email)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            User user = session.CreateQuery("from User u where u.username=:email")
                    .SetString("email", email)
                    .UniqueResult<User>();
            session.Close();
            return user;
        }

        public IList<User> getUser()
        {
            return control.getSession()
                .CreateQuery("from User")
                .List<User>();
        }

        public IList<User> getUser(string hql)
        {
            return control.getSession()
                .CreateQuery(hql)
                .List<User>();
        }

    }
}
